//
//  EmojViewController.swift
//  WeiBo_NB
//
//  Created by apple on 15/3/12.
//  Copyright (c) 2015年 Ai. All rights reserved.
//

import UIKit

class EmojViewController: UIViewController {

    // CollectionView
    @IBOutlet weak var myColectionView: UICollectionView!
    // CollectionViewCell-----Layout
    @IBOutlet weak var layOut: UICollectionViewFlowLayout!
    
    // 表情符号懒加载
    lazy var emoticonSection: [EmoticonsSection]?={
        return EmoticonsSection.loadEmoticons()
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
///  在该方法中调用，是因为此时视图基本布局已经完成
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        setupItemSize()
        
    }
    
    /// 设置ItemSize大小
    func setupItemSize() {
        
        let row : CGFloat = 3
        let line : CGFloat = 7
        let m : CGFloat = 10
        let screenW = self.myColectionView.frame.size.width
        let w = (screenW - (line + 1) * m) / line
        
        layOut.itemSize = CGSizeMake(w, w)
        myColectionView.pagingEnabled = true
        layOut.minimumInteritemSpacing = m
        layOut.minimumLineSpacing = m
        layOut.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layOut.sectionInset = UIEdgeInsetsMake(m, m, m, m)
    }

}

///  CollectionView数据源方法
extension  EmojViewController: UICollectionViewDataSource{
   
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
        return self.emoticonSection?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return emoticonSection![section].emoticons.count
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("EMOJCELL", forIndexPath: indexPath) as! EmoticonCell
//        if indexPath.section == 1{
//            
//            cell.backgroundColor = UIColor.redColor()
//        }else{
//            cell.backgroundColor = UIColor.greenColor()
//
//        }
        
        cell.emoticon = emoticonSection![indexPath.section].emoticons[indexPath.item]
        return cell
    }
    
}
/// 表情的 cell
class EmoticonCell: UICollectionViewCell {
    
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var emojiLabel: UILabel!
    
    var emoticon: Emoticon? {
        didSet {
            // 设置图像
            if let path = emoticon?.imagePath {
                iconView.image = UIImage(contentsOfFile: path)
            } else {
                iconView.image = nil
            }
            // 设置 emoji
            emojiLabel.text = emoticon?.emoji
            
            // 是否是删除按钮
            if emoticon!.isDeleteButton {
                iconView.image = UIImage(named: "compose_emotion_delete_highlighted")
            }
        }
    }
}